<?php

namespace app\course\controller;

use app\classes\controller\ClassesController;
use app\classes\model\ClassModel;
use app\course\model\CourseModel;
use app\course\model\CourseCategoryModel;
use app\course\service\CourseService;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;

class CourseController extends AdminBaseController
{
    public function index()
    {


        $param = $this->request->param();
        $categroyId = $this->request->param('category', 0, 'intval');
        $shop_id=$this->admin_shop_id;
        $param['shop_id']=$shop_id;
        $courseService = new CourseService();
        $data = $courseService->adminCourseList($param);
        $courseCateModel = new CourseCategoryModel();
        $categoryTree = $courseCateModel->courseCategoryTree($categroyId);

        if (empty($param['enabled']) && isset($param['enabled'])) {

            $b = 'selected';
            $this->assign('b', $b);
        } else if (!empty($param['enabled'])) {
            if ($param['enabled'] == 1) {
                $a = 'selected';
                $this->assign('a', $a);
            } else {
                $c = 'selected';
                $this->assign('c', $c);
            }

        }
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('courses', $data->items());

        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categroyId);

        $this->assign('page', $data->render());
        return $this->fetch();
    }

    public function add()
    {

        $parentId = $this->request->param('parent', 0, 'intval');
        $cousercart = new CourseCategoryModel();
        $categoriesTree = $cousercart->courseCategoryTree($parentId);

        $this->assign('categories_tree', $categoriesTree);
        return $this->fetch();
    }

    /**
     *  添加课程
     */
    public function addPost()
    {


        if ($this->request->isPost()) {
            //获取数据
            $data = $this->request->post();
            //课程表
            $course = new CourseModel();
            //资源表
            $asset = Db::name('asset');
            if ($data['category_id'] == 0) {
                $this->error('课程类别没有选择', url('Course/add'));
            }
            $result = $this->validate($data, 'Course');


            if ($result !== true) {
                $this->error($result);
            }
            if(!empty($_FILES['record']))
            {
                $type = pathinfo($_FILES['record']['name'], PATHINFO_EXTENSION);
                //  echo $type;
                $allow_type = ['rar', 'zip'];
                if (!in_array(strtolower($type), $allow_type)) {
                    $this->error('上传不是压缩文件');
                }
                $filereturn = $this->upload('record', $dir = './upload/courses/');
                $dir = substr($filereturn, 0, 8);
                $filepath = 'courses/' . $dir . '/' . $filereturn;

                //录音表 的表 asset
                $doc = $_FILES['record'];
                $asset_data = [];
                $asset_data['create_time'] = time();
                $asset_data['filename'] = $doc['name'];
                $asset_data['file_path'] = $filepath;
                $asset_data['suffix'] = $type;
                 $record_asset_id = $asset->insertGetId($asset_data);
                $data['record_asset_id']=$record_asset_id;
            }



            $data['create_time'] = date('Y-m-d H:i:s', time());
            $data['create_user_id'] = cmf_get_current_admin_id();

            if (isset($data['photo_names'])) {
                $asset_data = [];
                $asset_data['create_time'] = time();
                $asset_data['filename'] = $data['photo_names'][0];
                $asset_data['file_path'] = $data['photo_urls'][0];
                $asset_data['suffix'] = substr($data['photo_names'][0], strrpos($data['photo_names'][0], '.') + 1);
                $img_info = getimagesize($_SERVER['DOCUMENT_ROOT'] . '/upload/' . $data['photo_urls'][0]);
                $asset_data['file_size'] = $img_info['bits'];
                $asset_id = $asset->insertGetId($asset_data);
                $data['asset_id'] = $asset_id;
                unset($data['photo_names']);
                unset($data['photo_urls']);
            }
            if (!isset($data['is_year_one'])) {
                unset($data['one_reduce_price']);
            }
            if (!isset($data['is_year_two'])) {
                unset($data['two_reduce_price']);
            }
            if (!isset($data['is_year_three'])) {
                unset($data['three_reduce_price']);
            }

            $res = $course->allowField(true)->data($data, true)->save();
            if ($res) {

                //记录日志
                $id = $course->getLastInsID(); //座位的id
                $pk = $id; //主键
                $table = 'cmf_course';//数据表名
                $content = lang('ADD_COURSE', ['name' => $data['course_name']]);
                do_log($content, $pk, $table, time());

                $this->success('添加课程成功', url('Course/index'));
            } else {
                $this->error('添加课程失败');
            }
        }


    }

    public function edit()
    {
        $id = $this->request->param('id', '0', 'intval');
        $courseModel = new CourseModel();
        $course = $courseModel->where('id', $id)->find();
        //处理简要内容
        $course['summary'] = trim($course['summary']);
        //处理课程介绍
        $course['description'] = trim(htmlspecialchars_decode($course['description']), '');
        $category_id = $course['category_id'];
        //前台可见不可见的判断
        if ($course['enabled'] == 1) {
            $rr = 'checked';
            $this->assign('rr', $rr);
        } else {
            $tt = 'checked';
            $this->assign('tt', $tt);
        }

        //课程的model
        $CourseCategoryModel = new CourseCategoryModel();
        //课程类别
        $data = $CourseCategoryModel->courseCategoryTree($category_id);
        //获取资源的图片
        $asset_id = $course->asset_id;
        $asset_model = Db::name('asset')->where('id', $asset_id)->find();
        //获取压缩文件

        $record_asset_id = $course->record_asset_id;
        $record_asset_model = Db::name('asset')->where('id', $record_asset_id)->find();

        $this->assign('categories_tree', $data);
        $this->assign('course', $course);
        $this->assign('img', $asset_model);
        $this->assign('record_asset', $record_asset_model);
        return $this->fetch();
    }

    //提交修改的editPost
    public function editPost()
    {
        $courseModel = new CourseModel();
        $class_model = new ClassModel();

        //资源表
        $asset = Db::name('asset');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $data['category_id'] = $data['parent_id'];

            unset($data['parent_id']);
            $id = $this->request->post('id');
            $asset_id = $courseModel->where('id', $id)->value('asset_id');
            $record_asset_id = $courseModel->where('id', $id)->value('record_asset_id');

            if (empty($id)) {
                return $this->error('没有此课程');
            }
            if (empty(trim($data['course_name']))) {
                return $this->error('课程名字不能为空');
            }
            $result = $this->validate($data, 'Course');
            if ($result !== true) {
                $this->error($result);
            }

            if (!isset($data['is_year_one'])) {
                $data['is_year_one'] = 0;
                unset($data['one_reduce_price']);
            }
            if (!isset($data['is_year_two'])) {
                $data['is_year_two'] = 0;
                unset($data['two_reduce_price']);
            }
            if (!isset($data['is_year_three'])) {
                $data['is_year_three'] = 0;
                unset($data['three_reduce_price']);
            }
            $data['update_time'] = time();

            Db::startTrans();
            try {

                if (isset($data['photo_names'])) {
                    $asset_data = [];
                    $asset_data['create_time'] = time();
                    $asset_data['filename'] = $data['photo_names'][0];
                    $asset_data['file_path'] = $data['photo_urls'][0];
                    $asset_data['suffix'] = substr($data['photo_names'][0], strrpos($data['photo_names'][0], '.') + 1);

                    if (empty($asset_id)) {
                        $res = $asset->insert($asset_data);
                        $asset_id = $asset->getLastInsID();
                        if ($res) {
                            $data['asset_id'] = $asset_id;
                        }
                    } else {
                        $asset->where(['id' => $asset_id])->update($asset_data);
                    }
                    unset($data['photo_names']);
                    unset($data['photo_urls']);
                }

                if(!empty($_FILES['record']))
                {
                    $type = pathinfo($_FILES['record']['name'], PATHINFO_EXTENSION);
                    //  echo $type;
                    $allow_type = ['rar', 'zip'];
                    if (!in_array(strtolower($type), $allow_type)) {
                        $this->error('上传不是压缩文件');
                    }
                    $filereturn = $this->upload('record', $dir = './upload/courses/');
                    $dir = substr($filereturn, 0, 8);
                    $filepath = 'courses/' . $dir . '/' . $filereturn;

                    //录音表 的表 asset
                    $doc = $_FILES['record'];
                    $asset_data = [];
                    $asset_data['create_time'] = time();
                    $asset_data['filename'] = $doc['name'];
                    $asset_data['file_path'] = $filepath;
                    $asset_data['suffix'] = $type;
                    if (empty($record_asset_id)) {
                        $record_asset_id1 = $asset->insertGetId($asset_data);
                        if ($record_asset_id1) {
                            $data['record_asset_id'] = $record_asset_id1;
                        }
                    } else {
                        $asset->where(['id' => $record_asset_id])->update($asset_data);
                    }
                }

                $count = $class_model->where(['course_id' => $id])->count();
               $class_id = $class_model->where(['course_id' => $id])->column('id');


            //如果班级关联课程，需要修改排课
            if ($count > 0) {
                $course_hour = $courseModel->where(['id' => $id])->value('course_hour');
                $total_price = $courseModel->where(['id' => $id])->value('total_price');
                //如果课程的总价变了，班级的变了
                if (intval($data['total_price']) != intval($total_price)) {
                    $total_price = $data['total_price'];
                    if ($count == 1) {
                        //如果班级只有一个
                        $class_data = $class_model->where(['id' => $class_id[0]])->find(); //$class_id是数据
                        $incidental_price = $class_data['incidental_price'];
                        $signup_price = $class_data['signup_price'];
                        $total = $incidental_price+ $signup_price + $total_price;
                        $class_model->where(['id' => $class_id[0]])->update(['lesson_price' => $total_price, 'total_price' => $total]);
                    } elseif ($count > 1) {
                        foreach ($class_id as $k => $val) {
                            //如果班级只有多个
                            $class_data = $class_model->where(['id' => intval($val)])->find();
                            $incidental_price = $class_data['incidental_price'];
                            $signup_price = $class_data['signup_price'];
                            $total = intval($incidental_price) + intval($signup_price) + intval($total_price);
                            $class_model->where(['id' => intval($val)])->update(['lesson_price' => $total_price, 'total_price' => $total]);
                        }
                    }
                }
                //如果课程进度不相等 需要修改排课
                if (intval($course_hour) != intval($data['course_hour'])) {
                    $course_hour = $data['course_hour'];
                    $room_model=new ClassModel();
                    foreach ($data as $k => $v) {
                        $arr = $room_model->progress($data[$k]['id']);
                        $arr = json_decode($arr, True);
                        $data[$k]['progress'] = $arr['progress'];
                    }
                    if (count($class_id) == 1) {
                        //如果班级只有一个

                        $course_schema = $class_model->getCourseTime($class_id = $class_id[0], $course_start = 0, $course_hour = $course_hour, $shop_id = 1);
                        //$class_id编程一维数组了

                        $teacher_id = $class_model->where(['id' => $class_id])->value('teacher_id');
                        $classroom_id = $class_model->where(['id' => $class_id])->value('classroom_id');
                        Db::name('course_schedule')->where(['class_id' => $class_id])->delete();
                        foreach ($course_schema as $k => $v) {
                            //课程计划
                            $data_schema = [];
                            $data_schema['class_id'] = $class_id;
                            $data_schema['classroom_id'] = $classroom_id;
                            $data_schema['teacher_id'] = $teacher_id;
                            $data_schema['date'] = strtotime($v['date']);
                            $data_schema['start_time'] = $v['start_time'];
                            $data_schema['end_time'] = $v['end_time'];
                            $data_schema['schedule'] = $v['schedule'];
                            $data_schema['week'] = $v['cur_week'];
                            Db::name('course_schedule')->insert($data_schema);
                        }
                    } elseif (count($class_id) > 1) {
                        foreach ($class_id as $k => $val) {
                            //如果班级只有多个
                            $teacher_id = $class_model->where(['id' => intval($val)])->value('teacher_id');
                            $course_schema = $class_model->getCourseTime($class_id = intval($val), $course_start = 0, $course_hour = $course_hour, $shop_id = 1);
                            Db::name('course_schedule')->where(['class_id' => intval($val)])->delete();
                            //判断$course_schema不为空
                            if (!empty($course_schema)) {
                                foreach ($course_schema as $k1 => $v) {
                                    //课程计划
                                    $data_schema = [];
                                    $data_schema['class_id'] = intval($val);
                                    $data_schema['classroom_id'] = $v['classroom_id'];
                                    $data_schema['teacher_id'] = $teacher_id;
                                    $data_schema['date'] = strtotime($v['date']);
                                    $data_schema['start_time'] = $v['start_time'];
                                    $data_schema['end_time'] = $v['end_time'];
                                    $data_schema['schedule'] = $v['schedule'];
                                    $data_schema['week'] = $v['cur_week'];
                                    Db::name('course_schedule')->insert($data_schema);
                                }
                            }

                        }
                    }
                }

            }
                $result1 = $courseModel->allowField(true)->isUpdate(true)->data($data, true)->save(['id' => $id]);

                    //记录日志
                    $pk = $id; //主键
                    $table = 'course';//数据表名
                    $content = lang('EDIT_COURSE', ['name' => $data['course_name']]);
                    do_log($content, $pk, $table, time());
                    Db::commit();
                    $this->success('课程修改成功', url('Course/index'));
                } catch(Exception $e)
                {
                    Db::rollback();
                    $this->error('课程修改失败');
                }

        }
    }

    public function delete()
    {

        $courseModel = new CourseModel();
        $param = $this->request->param();
        $class_model = new ClassModel();
        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            $res = $courseModel->where('id', $id)->find();


            $count = $class_model->where(['course_id' => $id])->count();
            if ($count > 0) {
                $this->error('有班级存在关联课程不能删除');
            }
            //伪删除
            $result = $courseModel
                ->where('id', $id)
                ->update(['delete_time' => time()]);
            //真的删除
//            $result = $schoolCategory
//                ->where('id', $id)
//                ->delete();
            if ($result) {
                //记录日志
                $cur_time = time();
                $table = 'course';
                $pk = $id;
                $content = lang('DELETE_COURSE', ['name' => $res['course_name']]);
                do_log($content, $pk, $table, $cur_time);
                $this->success("删除成功！", '');
            }
            $this->success('删除失败', '');

        }
        //批量删除
        if (isset($param['ids'])) {
            $ids = $this->request->param('ids/a');
            $result = $courseModel->where(['id' => ['in', $ids]])->update(['delete_time' => time()]);
            foreach ($ids as $val) {
                $count = $class_model->where(['course_id' => intval($val)])->count();
                if ($count > 0) {
                    $this->error('有班级存在关联课程不能删除');
                }
            }
            if ($result) {
                //记录日志
                $pk = implode(',', $ids);
                $names = db::name('course')->whereIn('id', $ids)->field('course_name')->select();
                if ($names->count() > 0) {
                    $names_array = $names->toArray();
                    $names_array = array_column($names_array, 'course_name');
                    $name = implode(',', $names_array);
                    $content = lang('DELETE_COURSE', ['name' => $name]);
                    do_log($content, $pk, $table, $cur_time);
                }
                $this->success("删除成功！", '');
            }
        }
    }

    /*
     * 批量的可见或者不见
     */
    public function visible()
    {
        $cur_time = time();
        $table = 'course';
        $courseModel = new CourseModel();
        $param = $this->request->param();
        //批量的可见或者不可见
        if (isset($param['ids'])) {
            $ids = $this->request->param('ids/a');
            $first = $courseModel->where('id', $ids[0])->value('enabled');
            if ($first == 0) {
                $result = $courseModel->where(['id' => ['in', $ids]])->update(['enabled' => 1]);
            } else {
                $result = $courseModel->where(['id' => ['in', $ids]])->update(['enabled' => 0]);
            }
            if ($result) {
                //记录日志
//                $pk = implode(',', $ids);
//                $content = '批量可见或者不可见';
//                do_log($content, $pk, $table, $cur_time);
                $this->success("操作成功！", '');
            }
        }
    }

    /*
        * 批量的排序
        */
    public function lister_order()
    {
        $cur_time = time();
        $table = 'course';
        $courseModel = new CourseModel();
        $param = $this->request->param();
        $id = $param['id'];
        $list_order = $param['list_order'];
        $result = $courseModel->where(['id' => $id])->update(['list_order' => $list_order]);
        if ($result) {

            $this->success("排序成功！", '');
        } else {
            $this->success("您没有改动过排序内容！", '');
        }
    }
    function upload($name, $dir = './upload/', $allow_type = array('tar', 'zip','rar'))
    {

        if ($_FILES[$name]['error'] > 0) {
            /* switch($_FILES['pic']['error']){
                 case 1:
                     echo'';

            }*/
            echo '上传错误';
            return false;
        }
        //2.获取后缀名
        $type = pathinfo($_FILES[$name]['name'], PATHINFO_EXTENSION);
        //  echo $type;
        if (!in_array($type, $allow_type)) {
            echo '上传一个录音压缩文件过来';
            return false;
        }
        //3.起名字
        $filename = date('Ymd') . uniqid() . mt_rand(0, 9999) . '.' . $type;

        //4.保存路径

        $save_path = rtrim($dir, '/');
        $save_path .= '/';
        $save_path .= date('Ymd');
        // echo $save_path;
        if (!file_exists($save_path)) {
            mkdir($save_path, '0777', true);
            chmod($save_path, '0755');
        }
        $path = $save_path . '/' . $filename;

        if (!is_uploaded_file($_FILES[$name]['tmp_name'])) {
            return false;
        }
        if (!move_uploaded_file($_FILES[$name]['tmp_name'], $path)) {
        }

        return $filename;

    }
    /*
    * 下载
    */
    public function  down()
    {


        $asset_id=$this->request->param('record_asset_id');
        $filepath=Db::name('asset')->where('id',$asset_id)->value('file_path');
        $filename=Db::name('asset')->where('id',$asset_id)->value('filename');

        $path=$_SERVER['DOCUMENT_ROOT']."/upload/".$filepath;
//         $path=$_SERVER['HTTP_HOST']."/upload/".$filepath;


        //实现下载这个功能代码
        header('content-disposition:attachment;filename='.$filename);

//        dump(__FILE__);
//        dump(basename(__FILE__));
//        exit();
//        header('content-disposition:attachment;filename='.basename(__FILE__));
        //要把下载文件里面的内容打印到这个页面
        readfile($path);
    }

}
